package com.zhang.first.day02;

import com.zhang.first.utils.ClickEvent;
import com.zhang.first.utils.ClickEventSource;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @title: 基本转换算子 map  , flatMap
 * @author: zhang
 * @date: 2022/1/15 21:51
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickEventSource())
                .map(new MapFunction<ClickEvent, String>() {
                    @Override
                    public String map(ClickEvent value) throws Exception {
                        return value.name;
                    }
                });

        env
                .addSource(new ClickEventSource())
                .map(r -> r.name)
                .print();

        env
                .addSource(new ClickEventSource())
                .map(new Mymap())
                .print();

        env
                .addSource(new ClickEventSource())
                .map(r -> Tuple2.of(r.name, r.url))
                .returns(Types.TUPLE(Types.STRING, Types.STRING))
                .print();

        //可以使用flatMap实现map

        env
                .addSource(new ClickEventSource())
                .flatMap(new FlatMapFunction<ClickEvent, String>() {
                    @Override
                    public void flatMap(ClickEvent value, Collector<String> out) throws Exception {
                        out.collect(value.name);
                    }
                }).print();

        env.execute();
    }

    public static class Mymap implements MapFunction<ClickEvent, String> {

        @Override
        public String map(ClickEvent value) throws Exception {
            return value.name;
        }
    }
}
